import { Button, Checkbox, Form, Input } from "antd";
import React from "react";
import styles from "./LoginView.module.css";

import axios from "../../http/index";

import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";

import { loginAction } from "../../store/action/userAction";

const LoginView = () => {
  const navigate = useNavigate();

  const dispatch = useDispatch();

  const onFinish = (values) => {
    console.log("Success:", values);

    axios({
      url: "/user/login",
      method: "POST",
      data: {
        username: values.username,
        pwd: values.password,
      },
    })
      .then((res) => {
        console.log(res.data.data);
        if (res.data.code === "200") {
          dispatch(loginAction(res.data.data));
          navigate("/");
          sessionStorage.setItem("data", JSON.stringify(res.data.data));
        } else {
          console.log(res.data.msg);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };

  return (
    <div className={styles.login}>
      <Form
        className={styles.login_form}
        name="basic"
        initialValues={{
          remember: true,
        }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item className={styles.form_item}>
          <span className={styles.header}>欢迎登录供应链系统</span>
        </Form.Item>
        <Form.Item
          label="账号"
          name="username"
          rules={[
            {
              required: true,
              message: "请输入账号",
            },
          ]}
          className={styles.form_item}
        >
          <Input className={styles.form_input} />
        </Form.Item>

        <Form.Item
          className={styles.form_item}
          label="密码"
          name="password"
          rules={[
            {
              required: true,
              message: "请输入密码",
            },
          ]}
        >
          <Input.Password className={styles.form_input} />
        </Form.Item>

        <Form.Item
          className={styles.form_item1}
          name="remember"
          valuePropName="checked"
        >
          <Checkbox className={styles.checkbox}>记住账号</Checkbox>
        </Form.Item>

        <Button
          type="primary"
          htmlType="submit"
          className={styles.login_btn}
          block={true}
        >
          立即登录
        </Button>
      </Form>
    </div>
  );
};
export default LoginView;
